package com.quectel.core.module.securitypatrol.service.impl;


import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.securitypatrol.dao.SecurityPatrolDeviceSubjectDao;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolDeviceSubjectDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolSubjectDto;
import com.quectel.core.module.securitypatrol.entity.SecurityPatrolDeviceSubjectEntity;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolDeviceSubjectService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolSubjectService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:11
 */
@DubboService
public class SecurityPatrolDeviceSubjectServiceImpl implements SecurityPatrolDeviceSubjectService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityPatrolDeviceSubjectServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> SECURITY_PATROL_DEVICE_SUBJECT_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "SECURITY_PATROL_DEVICE_SUBJECT_CACHE_BY_ID:%d", id);

    @Autowired
    private SecurityPatrolDeviceSubjectDao securityPatrolDeviceSubjectDao;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SecurityPatrolSubjectService securityPatrolSubjectService;

    @Override
    public void deleteByDeviceId(Long deviceId) {
        securityPatrolDeviceSubjectDao.delete(new QueryWrapper<SecurityPatrolDeviceSubjectEntity>().eq("device_id", deviceId));
    }


    /**
     * 设备id 和 安保巡检项目绑定
     *
     * @param deviceId
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindSubjects(Long deviceId, Long[] ids, Byte categroy) {
        // ids 为空,说明是清空操作
        if (ids.length == 0) {
            this.deleteByDeviceId(deviceId);
        } else {
            // 先删除
            this.deleteByDeviceId(deviceId);
            // 新增记录
            for (int i = 0; i < ids.length; i++) {
                SecurityPatrolDeviceSubjectDto deviceSubjectDto = new SecurityPatrolDeviceSubjectDto();
                deviceSubjectDto.setDeviceId(deviceId);
                deviceSubjectDto.setSubjectId(ids[i]);
                deviceSubjectDto.setCategory(categroy);
                this.save(deviceSubjectDto);
            }
        }

    }

    @Override
    public SecurityPatrolDeviceSubjectDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                SECURITY_PATROL_DEVICE_SUBJECT_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public SecurityPatrolDeviceSubjectDto selectById(Long id) {
        SecurityPatrolDeviceSubjectEntity entity = securityPatrolDeviceSubjectDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, SecurityPatrolDeviceSubjectDto.class));
    }

    @Override
    public List<SecurityPatrolDeviceSubjectDto> queryList(Map<String, Object> params) {
        List<SecurityPatrolDeviceSubjectEntity> list = securityPatrolDeviceSubjectDao.queryList(params);
        List<SecurityPatrolDeviceSubjectDto> result = CopyUtils.copyList(list, SecurityPatrolDeviceSubjectDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private SecurityPatrolDeviceSubjectDto paddingField(SecurityPatrolDeviceSubjectDto dto) {
        if (dto != null) {
            dto.setDeviceDto(deviceService.selectCacheById(dto.getDeviceId()));

            if (dto.getDeviceId() != null) {
                List<SecurityPatrolSubjectDto> subjectList = new ArrayList<>();
                Map<String, Object> params = new HashMap<>();
                params.put(LambdaUtil.getFieldName(SecurityPatrolDeviceSubjectDto::getDeviceId), dto.getDeviceId());
                List<SecurityPatrolDeviceSubjectEntity> securityPatrolDeviceSubjectEntities
                        = securityPatrolDeviceSubjectDao.queryList(params);
                if (securityPatrolDeviceSubjectEntities != null && securityPatrolDeviceSubjectEntities.size() > 0) {
                    for (SecurityPatrolDeviceSubjectEntity entity : securityPatrolDeviceSubjectEntities) {
                        SecurityPatrolSubjectDto securityPatrolSubjectDto = securityPatrolSubjectService.selectById(entity.getSubjectId());
                        subjectList.add(securityPatrolSubjectDto);
                    }
                    dto.setSubjectList(subjectList);
                }

            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return securityPatrolDeviceSubjectDao.queryTotal(params);
    }

    @Override
    public Long save(SecurityPatrolDeviceSubjectDto dto) {
        SecurityPatrolDeviceSubjectEntity entity = CopyUtils.copyObj(dto, SecurityPatrolDeviceSubjectEntity.class);
        entity.setId(Snowflake.nextId());
        securityPatrolDeviceSubjectDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(SecurityPatrolDeviceSubjectDto dto) {
        SecurityPatrolDeviceSubjectEntity entity = CopyUtils.copyObj(dto, SecurityPatrolDeviceSubjectEntity.class);
        securityPatrolDeviceSubjectDao.updateById(entity);
        CacheKit.invalidRedisCache(SECURITY_PATROL_DEVICE_SUBJECT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(SecurityPatrolDeviceSubjectDto dto) {
        SecurityPatrolDeviceSubjectEntity entity = CopyUtils.copyObj(dto, SecurityPatrolDeviceSubjectEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, securityPatrolDeviceSubjectDao);

        CacheKit.invalidRedisCache(SECURITY_PATROL_DEVICE_SUBJECT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        securityPatrolDeviceSubjectDao.deleteById(id);

        CacheKit.invalidRedisCache(SECURITY_PATROL_DEVICE_SUBJECT_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
